package com.tensquare.article.controller;

import com.tensquare.article.pojo.Article;
import com.tensquare.article.service.ArticleService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    ArticleService articleService;

    //通过文章订阅文章发布者subscribe
    @RequestMapping(value = "/subscribe/{articleId}/{userId}",method = RequestMethod.POST)
    public Result subscribe(@PathVariable String articleId,@PathVariable String userId){
        boolean b = articleService.articleId(articleId, userId);
        if (b){
            //订阅成功
            return new Result(b, StatusCode.OK,"订阅成功");
        }else {
            //取消订阅
            return new Result(!b, StatusCode.OK,"取消订阅");
        }
    }
    //查询所有
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll(){
        List<Article> all = articleService.findAll();
       return new Result(true, StatusCode.OK,null,all);
    }

   // 分页条件查询
    @RequestMapping(value = "/search/{page}/{size}",method = RequestMethod.POST)
    public Result findByPage(@RequestBody(required=false) Article article,
                             @PathVariable Integer page,
                             @PathVariable Integer size
                             ){
        List<Article> byPage = articleService.findByPage(page, size, article);
        long size1 = byPage.size();
        PageResult<Article> articlePageResult = new PageResult<>(size1, byPage);
        return new Result(true,StatusCode.OK,null,articlePageResult);
    }

    //增加文章
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody Article article){
        articleService.save(article);
        return new Result(true,StatusCode.OK,null);
    }

    //根据id查询文章
    @RequestMapping(value = "{id}",method = RequestMethod.GET)
    public Result findById(@PathVariable String id){
        Article byId = articleService.findById(id);
        return new Result(true,StatusCode.OK,null,byId);
    }

    //修改文章
    @RequestMapping(value = "{id}",method = RequestMethod.PUT)
    public Result add(@PathVariable String id,@RequestBody Article article){
        articleService.update(id,article);
        return new Result(true,StatusCode.OK,null);
    }

    //根据id删除文章
    @RequestMapping(value = "{id}",method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id){
        articleService.delete(id);
        return new Result(true,StatusCode.OK,null);
    }
}
